// pages/courseDetail/courseDetail.js
const {
    getCourseDetail,
} = require('../../services/courseReq')
const {
    buyCourse
} = require('../../services/courseDetailReq')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        obj: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.showLoading({
            title: '加载中',
        })
        const id = options.id
        getCourseDetail(id, res => {
            console.log(res)
            this.setData({
                obj: res.data.data
            })
            wx.hideLoading()
        })
    },


    // 立即购买
    handleBuy() {

        const volunteerId = wx.getStorageSync('volunteerInfo').volunteerId;
        if (!volunteerId) {
            return wx.showToast({
                title: "请登陆后再购买",
                icon: "error",
                duration: "2s",
                success(res) {
                    wx.navigateTo({
                        url: "../login/login"
                    })
                }
            })
        }
        const courseId = this.data.obj.courseId
        buyCourse(courseId, volunteerId, res => {
            wx.showLoading({
                title: '下单中',
                mask: true
            })
            if (res.data.code !== 0) {
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none'
                })
            } else {
                let req = res.data.data

                if (req.data.code) {
                    return wx.showToast({
                        title: '出错啦',
                        icon: "error"
                    })
                }
                req.data["package"] = "prepay_id=" + req.data["package"]
                // console.log( req.data["package"])
                wx.requestPayment({
                    ...req.data,
                    paySign: req.data.sign,
                    success(res) {
                        wx.hideLoading();

                        return wx.showToast({
                            title: '支付成功',
                        })
                    },
                    fail(res) {
                        wx.hideLoading();


                        return wx.showToast({
                            title: '你已经取消支付',
                            icon: "error"
                        })

                    },

                })
            }
        })

    }
})
